package com.jason.product.service;


import com.jason.product.dao.TccProductMapper;
import io.seata.rm.tcc.api.BusinessActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service
public class ProductService implements IProductService{
    Logger logger = LoggerFactory.getLogger(getClass());
    @Resource
    TccProductMapper tccProductMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean prepare(BusinessActionContext businessActionContext,Integer id, Integer number) {
        logger.info("执行prepare");
        tccProductMapper.updateNumberById(number,id);
        /**if(1==1) {
             //开启此处时，account-service已经提交了本地事务，所以会被回滚，product和order的prepare事务没有提交，所以不会执行rollback
            throw new RuntimeException("测试第三步提交失败");
        }*/
        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean commit(BusinessActionContext businessActionContext) {
        logger.info("执行commit");
        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean rollback(BusinessActionContext businessActionContext) {
        logger.info("执行rollback");
        Integer id = businessActionContext.getActionContext("id",Integer.class);
        Integer number = businessActionContext.getActionContext("number",Integer.class);
        tccProductMapper.updateNumberById(number,id);
        return true;
    }
}
